import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
/*
 * StatefulWidget 的生命周期实现基于原生实现
 */
mixin StateLifecycle<T extends StatefulWidget> on State<T> implements RouteAware, WidgetsBindingObserver, IStateLifecycle {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final route = ModalRoute.of(context);
    if (route != null && route is PageRoute) {
      routeObserver.subscribe(this, route);
    }
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didPop() {
    onStop();
  }

  @override
  void didPopNext() {
    onResume();
  }

  @override
  void didPush() {
    onStart();
  }

  @override
  void didPushNext() {
    onPause();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      onResume();
    } else if (state == AppLifecycleState.paused) {
      onPause();
    }
  }

  //  =========================== 默认空实现 ===========================

  @override
  void didChangeViewFocus(ViewFocusEvent event) {}
  
  @override
  void didChangeAccessibilityFeatures() {}

  @override
  void didChangeLocales(List<Locale>? locales) {}

  @override
  void didChangeMetrics() {}

  @override
  void didChangePlatformBrightness() {}

  @override
  void didChangeTextScaleFactor() {}

  @override
  void didHaveMemoryPressure() {}

  @override
  Future<bool> didPopRoute() {
    return Future<bool>.value(false);
  }

  @override
  Future<bool> didPushRoute(String route) {
    return Future<bool>.value(false);
  }

  @override
  Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
    return didPushRoute(routeInformation.location!);
  }

  @override
  Future<AppExitResponse> didRequestAppExit() async {
    return AppExitResponse.exit;
  }

  @override
  void onStart() {}

  @override
  void onStop() {}

  @override
  void onResume() {}

  @override
  void onPause() {}

  // 实现 WidgetsBindingObserver 中的抽象方法
  @override
  Future<bool> handleCancelBackGesture() async {
    return false;
  }

  @override
  Future<bool> handleCommitBackGesture() async {
    return false;
  }

  @override
  bool handleStartBackGesture(PredictiveBackEvent backEvent) {
    return false;
  }

  @override
  void handleUpdateBackGestureProgress(PredictiveBackEvent backEvent) {}
}

// 自定义生命周期回调接口
abstract class IStateLifecycle {
  void onStart(); //启动页面
  void onStop(); //结束页面
  void onResume(); //重新可见
  void onPause(); //被覆盖隐藏
}
